<template>
  <a-row v-if="itemCol" type="flex" :gutter="0" style="color: inherit; line-height: inherit">
    <a-col class="descriptions-label" :span="itemCol.label" :style="getLabelStyle($attrs.labelStyle)">
      <slot name="label" v-bind="Object.assign({}, $attrs)">
        <span>{{ $attrs.label }}</span>
      </slot>
      <span v-if="$attrs.semi !== false && $attrs.semi !== null">：</span>
    </a-col>
    <a-col class="descriptions-wrapper" :span="itemCol.wrapper" :style="getWrapperStyle($attrs.wrapperStyle)">
      <slot name="wrapper" v-bind="Object.assign({}, $attrs, { text })">
        <span>{{ text }}</span>
      </slot>
    </a-col>
  </a-row>
  <div v-else>
    <span class="descriptions-label" :style="getLabelStyle($attrs.labelStyle)">
      <slot name="label" v-bind="Object.assign({}, $attrs)">
        <span>{{ $attrs.label }}</span>
      </slot>
      <span v-if="$attrs.semi !== false && $attrs.semi !== null">：</span>
    </span>
    <span class="descriptions-wrapper" :style="getWrapperStyle($attrs.wrapperStyle)">
      <slot name="wrapper" v-bind="Object.assign({}, $attrs, { text })">
        <span>{{ text }}</span>
      </slot>
    </span>
  </div>
</template>

<script>
import { get } from 'lodash-es';
import { NONE_TEXT } from '../../config/index.js';

export default {
  name: 'description',
  computed: {
    itemCol() {
      const isNum = (num) => typeof num === 'number' && Number.isFinite(num);
      let { labelCol, wrapperCol } = this.$attrs;
      labelCol = Number(labelCol);
      wrapperCol = Number(wrapperCol);
      if (!isNum(labelCol) && !isNum(wrapperCol)) {
        return null;
      }
      return {
        label: isNum(labelCol) ? labelCol : 24 - (wrapperCol || 0),
        wrapper: isNum(wrapperCol) ? wrapperCol : 24 - (labelCol || 0),
      };
    },
    text() {
      const { dataSource, key, field, format, noneText } = this.$attrs;
      const text = get(dataSource, key || field);
      if (typeof format === 'function') {
        return format(text, dataSource, this.$attrs) || noneText || NONE_TEXT;
      }
      return text || noneText || NONE_TEXT;
    },
  },
  methods: {
    merge() {
      const args = [].slice.call(arguments, 0);
      return Object.assign([].concat({}, args));
    },
    getLabelStyle(labelStyle) {
      return this.merge({ opacity: 0.5, color: 'inherit', lineHeight: 'inherit' }, labelStyle);
    },
    getWrapperStyle(wrapperStyle) {
      return this.merge({ opacity: 1, color: 'inherit', lineHeight: 'inherit' }, wrapperStyle);
    },
  },
};
</script>

<style lang="less"></style>
